<template>
  <div>
    <el-row :gutter="20">
      <el-col :xs="24" :span="8" :class="{ mb_s: isPhone }">
        <el-card shadow="hover" class="mgb20" style="height: 252px">
          <div class="user-info">
            <UserAvatar :src="userInfo.avatarUrl" :size="120" />
            <div class="user-info-cont">
              <div class="user-info-name">{{ userInfo.nickname }}</div>
              <div>{{ userInfo.roleName }}</div>
            </div>
          </div>
          <div class="user-info-list">
            上次登录时间：
            <span>{{ userInfo.lastLoginTime }}</span>
          </div>
          <div class="user-info-list">
            上次登录地点：
            <span>{{ userInfo.lastLoginArea || "未知" }}</span>
          </div>
        </el-card>

        <el-card shadow="hover" style="height: 252px">
          <template #header>
            <div class="clearfix">
              <span>任务占比</span>
            </div>
          </template>
          <div>简单</div>
          <el-progress :percentage="71.3" color="#42b983"></el-progress>
          <div>一般</div>
          <el-progress :percentage="24.1"></el-progress>
          <div>较难</div>
          <el-progress :percentage="13.7" color="#f1e05a"></el-progress>
          <div>很难</div>
          <el-progress :percentage="5.9" color="#f56c6c"></el-progress>
        </el-card>
      </el-col>

      <el-col :xs="24" :span="16">
        <el-row :gutter="20" class="mgb20">
          <el-col :xs="24" :span="8" :class="{ mb_s: isPhone }">
            <el-card shadow="hover" :body-style="{ padding: '0px' }">
              <div class="grid-content grid-con-1">
                <i class="el-icon-user-solid grid-con-icon"></i>
                <div class="grid-cont-right">
                  <div class="grid-num">{{ totalCount.dayReportCount }}</div>
                  <div>当年日报提交总数</div>
                </div>
              </div>
            </el-card>
          </el-col>

          <el-col :xs="24" :span="8" :class="{ mb_s: isPhone }">
            <el-card shadow="hover" :body-style="{ padding: '0px' }">
              <div class="grid-content grid-con-2">
                <i class="el-icon-message-solid grid-con-icon"></i>
                <div class="grid-cont-right">
                  <div class="grid-num">{{ totalCount.messageCount }}</div>
                  <div>系统消息</div>
                </div>
              </div>
            </el-card>
          </el-col>

          <el-col :xs="24" :span="8">
            <el-card shadow="hover" :body-style="{ padding: '0px' }">
              <div class="grid-content grid-con-3">
                <i class="el-icon-s-goods grid-con-icon"></i>
                <div class="grid-cont-right">
                  <div class="grid-num">{{ totalCount.weekReportCount }}</div>
                  <div>周报提交总数量</div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <el-card
          shadow="hover"
          style="height: 403px; display: flex; flex-direction: column"
          :body-style="{
            flex: 1,
          }"
        >
          <template #header>
            <div class="clearfix">
              <span>待办事项</span>
              <el-button
                style="float: right; padding: 3px 0"
                type="text"
                @click="addTodoData"
              >
                添加
              </el-button>
            </div>
          </template>
          <!-- 待办事项列表 -->
          <vxe-table
            v-loading="tableLoading"
            :data="todoList"
            ref="xTable"
            align="center"
            :show-header="false"
            height="100%"
            border="inner"
            show-overflow="tooltip"
            highlight-hover-row
            highlight-current-row
            class="xTable"
            :checkbox-config="{
              checkField: 'checked',
              trigger: 'row',
              checkMethod: tableCheckMethod,
            }"
            @cell-dblclick="cellDbClick"
          >
            <!-- <vxe-column type="checkbox" width="42" fixed="left"></vxe-column> -->

            <vxe-column type="seq" title="序号" width="42"></vxe-column>

            <vxe-column title="标题" align="left" min-width="200">
              <template #default="{ row }">
                <div
                  class="todo-item"
                  :class="{
                    'todo-item-del': row.isFinish === '1',
                  }"
                >
                  {{ row.title }}
                </div>
              </template>
            </vxe-column>

            <vxe-column field="todoTime" title="待办时间" width="130">
              <template #default="{ row }">
                <span style="font-weight: 600">
                  {{ row.todoTime }}
                </span>
              </template>
            </vxe-column>

            <vxe-column #default="{ row }" width="90" title="操作">
              <div @click.stop="">
                <el-tooltip
                  v-if="row.isFinish !== '1'"
                  content="完成"
                  placement="top"
                >
                  <Finished
                    class="icon icon_btn green without-outline"
                    @click="handleIsFinish(row, '1')"
                  />
                </el-tooltip>
                <!-- <el-tooltip content="编辑" placement="top">
                  <Edit class="icon icon_btn yellow without-outline" />
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <Delete class="icon icon_btn red without-outline" />
                </el-tooltip> -->
              </div>
            </vxe-column>
          </vxe-table>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :xs="24" :span="12" :class="{ mb_s: isPhone }">
        <el-card shadow="hover">
          <schart
            ref="schart1Ref"
            class="schart"
            canvasId="bar"
            :options="options"
          ></schart>
        </el-card>
      </el-col>

      <el-col :xs="24" :span="12">
        <el-card shadow="hover">
          <schart
            ref="schart2Ref"
            class="schart"
            canvasId="line"
            :options="options2"
          ></schart>
        </el-card>
      </el-col>
    </el-row>

    <!-- 代办事项弹窗 -->
    <ToDoFormDialog ref="todoFormDialogRef" />
  </div>
</template>

<script>
import Schart from "vue-schart";
import {
  ref,
  reactive,
  computed,
  getCurrentInstance,
  onUnmounted,
  onActivated,
  nextTick,
} from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import UserAvatar from "../../components/UserAvatar.vue";
import ToDoFormDialog from "../todo/components/TodoFormDialog.vue";
// import TimeEvent from "../../utils/worker/TimeEventClass";

export default {
  name: "dashboard",
  components: { Schart, UserAvatar, ToDoFormDialog },
  setup() {
    const { proxy } = getCurrentInstance();
    const $api = proxy.$api;
    const store = useStore();
    const router = useRouter();
    const userInfo = computed(() => store.state.user.userInfo);
    const isPhone = computed(() => store.state.isPhone);

    const tableLoading = ref(false);
    const xTable = ref(null);
    const schart1Ref = ref(null);
    const schart2Ref = ref(null);

    const todoFormDialogRef = ref(null);

    const totalCount = reactive({
      dayReportCount: 0,
      messageCount: 0,
      weekReportCount: 0,
    });

    const options = reactive({
      type: "bar",
      title: {
        text: "最近一周日报提交数量统计图",
      },
      xRorate: 25,
      labels: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
      datasets: [
        {
          label: "日报",
          data: [0, 0, 0, 0, 0, 0, 0],
        },
        // {
        //   label: "百货",
        //   data: [164, 178, 190, 135, 160, 100, 50],
        // },
        // {
        //   label: "食品",
        //   data: [144, 198, 150, 235, 120, 100, 50],
        // },
      ],
    });

    const options2 = reactive({
      type: "line",
      title: {
        text: "今年每月日报提交次数趋势图",
      },
      labels: [
        "1月",
        "2月",
        "3月",
        "4月",
        "5月",
        "6月",
        "7月",
        "8月",
        "9月",
        "10月",
        "11月",
        "12月",
      ],
      datasets: [
        {
          label: "日报",
          data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        },
        // {
        //   label: "周报",
        //   data: [4, 3, 4, 4, 4],
        // },
        // {
        //   label: "食品",
        //   data: [74, 118, 200, 235, 90],
        // },
      ],
    });

    const todoList = ref([]);

    // 查询今日待办
    const getTodoList = () => {
      tableLoading.value = true;
      $api.todo
        .listTodayWaitDo({})
        .then((res) => {
          tableLoading.value = false;
          todoList.value = res.data.map((item) => {
            return {
              ...item,
              checked: item.isFinish === "1",
            };
          });
        })
        .catch((err) => {
          tableLoading.value = false;
          console.error("getTodoList error: ", err);
        });
    };

    // 设置待办是否完成
    const handleIsFinish = (row, isFinish) => {
      ElMessageBox.confirm(
        `确定要${isFinish === "1" ? "完成" : "取消完成"}【${
          row.title.length > 10 ? row.title.slice(0, 10) + "..." : row.title
        }】吗？`,
        "提示",
        { type: "warning" }
      )
        .then(() => {
          toggleIsFinish(row.id, isFinish);
        })
        .catch(() => {});
    };

    // 设置待办是否完成接口
    const toggleIsFinish = (id, isFinish) => {
      tableLoading.value = true;
      $api.todo
        .toggleIsFinish({
          id,
          isFinish,
        })
        .then((res) => {
          ElMessage.success("操作成功！");
          getTodoList();
        })
        .catch((err) => {
          console.error("toggleIsFinish error: ", err);
        })
        .finally(() => {
          tableLoading.value = false;
        });
    };

    /**
     * 统计一周数量和一年数量
     */
    const getStatistics = () => {
      $api.report
        .getStatistics()
        .then((res) => {
          console.log("getStatistics => res", res);
          const weekReportRecordCountList = res.data.weekReportRecordCountList;
          const yearReportRecordCountList = res.data.yearReportRecordCountList;
          if (weekReportRecordCountList.length) {
            options.datasets[0].data = weekReportRecordCountList.map(
              (cell) => cell.count
            );
          } else {
            options.datasets[0].data = [0, 0, 0, 0, 0, 0, 0];
          }
          if (yearReportRecordCountList.length) {
            options2.datasets[0].data = yearReportRecordCountList.map(
              (cell) => cell.count
            );
          } else {
            options.datasets[0].data = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
          }
          totalCount.dayReportCount = res.data.yearReportRecordTotal || 0;
        })
        .catch((err) => {
          console.error("getStatistics error: ", err);
        });
    };

    const addTodoData = () => {
      // todoFormDialogRef.value && todoFormDialogRef.value.open();
      router.push("/TodoManage");
    };

    // 列表勾选行的禁用
    const tableCheckMethod = ({ row }) => {
      return false;
    };

    const cellDbClick = ({ row }) => {
      nextTick(() => {
        todoFormDialogRef.value.open(row, true);
      });
    };

    /**
     * 初始化
     */
    getStatistics();

    // const timeEvent = new TimeEvent();
    // timeEvent.addOnceEvent("2022/01/27 00:30:00", function () {
    //   console.log("回调被执行了！ ===> aa1", aa);
    // });
    // timeEvent.addOnceEvent("2022/01/27 00:30:10", function () {
    //   console.log("回调被执行了！ ===> aa2", aa);
    // });
    // timeEvent.addOnceEvent("2022/01/27 00:30:20", function () {
    //   console.log("回调被执行了！ ===> aa3", aa);
    // });

    onUnmounted(() => {
      // timeEvent.destroy();
    });

    onActivated(() => {
      getTodoList();
    });

    return {
      options,
      options2,
      todoList,
      userInfo,
      totalCount,
      isPhone,
      getStatistics,
      tableLoading,
      xTable,
      addTodoData,
      todoFormDialogRef,
      schart1Ref,
      schart2Ref,
      tableCheckMethod,
      toggleIsFinish,
      handleIsFinish,
      cellDbClick,
    };
  },
};
</script>

<style lang="less" scoped>
.el-row {
  margin-bottom: 20px;
}

.grid-content {
  display: flex;
  align-items: center;
  height: 100px;
}

.grid-cont-right {
  flex: 1;
  text-align: center;
  font-size: 14px;
  color: #999;
}

.grid-num {
  font-size: 30px;
  font-weight: bold;
}

.grid-con-icon {
  font-size: 50px;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
  color: #fff;
}

.grid-con-1 .grid-con-icon {
  background: rgb(45, 140, 240);
}

.grid-con-1 .grid-num {
  color: rgb(45, 140, 240);
}

.grid-con-2 .grid-con-icon {
  background: rgb(100, 213, 114);
}

.grid-con-2 .grid-num {
  color: rgb(45, 140, 240);
}

.grid-con-3 .grid-con-icon {
  /* background: rgb(242, 94, 67); */
  background: #e6a23c;
}

.grid-con-3 .grid-num {
  /* color: rgb(242, 94, 67); */
  color: rgb(45, 140, 240);
}

.user-info {
  display: flex;
  align-items: center;
  padding-bottom: 20px;
  border-bottom: 2px solid #ccc;
  margin-bottom: 20px;
}

.user-avator {
  width: 120px;
  height: 120px;
  border-radius: 50%;
}

.user-info-cont {
  padding-left: 50px;
  flex: 1;
  font-size: 14px;
  color: #999;
}

.user-info-cont div:first-child {
  font-size: 30px;
  color: #222;
}

.user-info-list {
  font-size: 14px;
  color: #999;
  line-height: 25px;
}

.user-info-list span {
  margin-left: 70px;
}

.mgb20 {
  margin-bottom: 20px;
}

.todo-item {
  font-size: 14px;
}

.todo-item-del {
  text-decoration: line-through;
  color: #999;
}

.schart {
  width: 100%;
  height: 300px;
}

.icon_btn {
  cursor: pointer;
  width: 22px;
  height: 22px;
  &.green:hover {
    color: #67c23a;
  }
  &.yellow:hover {
    color: #e6a23c;
  }
  &.red:hover {
    color: #f56c6c;
  }
}

.icon_btn + .icon_btn {
  margin-left: 15px;
}
</style>
